const express = require('express');
const app = express();
app.listen(3000, () => { console.log('服务器已开启') })

// 引入
const mysql = require('mysql');

// 配置用户信息
const con = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: 'root',
    database: 'demo1',
});

// 连接mysql
con.connect();

// post接参
app.use(express.urlencoded({ extended: false }));


// 注册逻辑
app.post('/register', (req, res) => {
    // 封装
    function fn() {
        return new Promise((resolve, reject) => {
            // 接参
            let { username, password } = req.body;
            // console.log(username, password);
            // 判断用户名是否存在
            let sql = `select * from member where username='${username}'`;
            con.query(sql, (err, result) => {
                console.log(err, result);
                if (err) {
                    res.send({ code: 500, msg: err })
                    return;
                }
                if (result.length > 0) {
                    res.send({ code: 400, msg: '用户名已存在' });
                    return;
                }
                resolve({ username, password });
            })

        })

    }

    // 使用
    async function fn2() {

        // 不存在添加到表中
        let { username, password } = await fn();
        console.log(username, password);
        let sql = `insert into member (username,password) values('${username}',' ${password}')`
        con.query(sql, (err, result) => {
            if (err) {
                res.send({ code: 500, msg: err });
                return;
            }
            if (result.insertId > 0) {
                res.send({ code: 200, msg: '注册成功' })
            } else {
                res.send({ code: 400, msg: '请稍后再试' })
            }
        })
    }
    fn2();
});

// 登录逻辑
app.post('/login', (req, res) => {
    // 接参
    let { username, password } = req.body;
    console.log(username, password);

    // 判断用户名是否存在
    let sql = `select * from member where username='${username}' and password='${password}'`;
    con.query(sql, (err, result) => {
        if (err) {
            res.send({ code: 500, msg: err });
            return;
        }
        if (result.length > 0) {
            res.send({ code: 200, msg: '登录成功' })

        } else {
            res.send({ code: 400, msg: '登录失败' })
        }
    })
})

